import React, { lazy } from 'react'
import{ Route } from 'react-router-dom'
import { TabBar } from 'antd-mobile'

// 导入自定义样式文件
import './index.css'

// 导入四个组件
import Index from '../Index'

// 改造动态载入组件
// import List from '../List'
const List = lazy(() => import('../List'))
// import News from '../News'
const News = lazy(() => import('../News'))
// import Profile from '../Profile'
const Profile = lazy(() => import('../Profile'))

export default class Home extends React.Component {
  constructor(props) {
    super(props);
    // TabItem数据内容
    const tabItems = [
      {
        'title': '首页',
        'key': 'index',
        'icon': 'icon-ind',
        'path': '/home',
      },
      {
        'title': '找房',
        'key': 'list',
        'icon': 'icon-findHouse',
        'path': '/home/list',
      },
      {
        'title': '资讯',
        'key': 'news',
        'icon': 'icon-infom',
        'path': '/home/news',
      },
      {
        'title': '我的',
        'key': 'my',
        'icon': 'icon-my',
        'path': '/home/profile',
      }
    ]
    this.state = {
      // 默认选中菜单
      selectedTab: this.props.location.pathname,
      tabItems: tabItems,
    };
  }

  componentDidUpdate(prevProps) {
    // 问题：当App组件不是第一次渲染或者不是点击时，路由地址切换不会导致图标高亮显示的切换
    // 解决：1. 在componentDidUpdate中判断前后路由地址是否发生切换（setState需要放在判断条件中，否则会导致componentDidUpdate无限循环调用）
    //       2. 在路由地址发生切换时，setState改变selectedTab值
    if (prevProps.location.pathname !== this.props.location.pathname) {
      this.setState({
        selectedTab: this.props.location.pathname
      })
    }
  }

  render() {
    return (
      <div className="home">
        <Route exact path="/home" component={Index}></Route>
        <Route path="/home/list" component={List}></Route>
        <Route path="/home/news" component={News}></Route>
        <Route path="/home/profile" component={Profile}></Route>

        <TabBar
          unselectedTintColor="#949494"
          tintColor="#057748"
          barTintColor="#fffbf0"
        >
          {
            this.state.tabItems.map((item, id) => {
              return (
                <TabBar.Item
                  title = {item.title}
                  key = {item.key}
                  icon = {
                    <i className = {`iconfont ${item.icon}`} />
                  }
                  selectedIcon  = {
                    <i className = {`iconfont ${item.icon}`} />
                  }
                  selected={this.state.selectedTab === item.path}
                  onPress = {
                    () => {
                      this.setState({
                        selectedTab: item.path
                      })
                      this.props.history.push(item.path)
                    }
                  }
                >
                </TabBar.Item>
              )
            })
          }
        </TabBar>
      </div>
    )
  }
}